package com.doit.demo.day02.sources;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;

import java.util.Random;

/**
 * @DATE 2022/2/15/16:39
 * @Author MDK
 * @Version 2021.2.2
 *
 *
 *  自定义并行的Source
 *  第一种,实现ParallelSourceFunction接口
 *  第二种,继承RichParallelSourceFunction抽象类
 *
 *
 **/
public class CustomParSource1 {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> nums = env.addSource(new ParallelSourceFunction<String>() {
            boolean flag = true;

            @Override
            public void run(SourceContext<String> sourceContext) throws Exception {
                Random r = new Random();
                while (flag) {
                    Thread.sleep(2000);
                    sourceContext.collect(r.nextInt() + "");
                }
            }

            @Override
            public void cancel() {
                flag = false;
            }
        });

        System.out.println("实现ParallelSourceFunction自定义的Source并行度:" + nums.getParallelism());
        nums.print();
        env.execute();
    }
}
